package repository

import (
	"egoal.com/DistributionGo/core"
	"github.com/jinzhu/gorm"
)

type UserRepository struct {
	Db *gorm.DB `inject:"db"`
}

func (u *UserRepository) GetAllUsers() ([]*core.User, error) {
	tsql := `select Id,ConcurrencyStamp,Email,PhoneNumber,UserName from AspNetUsers`
	users := make([]*core.User, 0)
	err := u.Db.Raw(tsql).Find(&users).Error
	if err != nil {
		return nil, err
	}

	/* 	rows, err := u.Db.Raw(tsql).Rows()
	   	if err != nil {
	   		return nil, err
	   	}
	   	defer rows.Close()

	   	for rows.Next() {
	   		user := new(core.User)
	   		err = u.Db.ScanRows(rows, user)
	   		if err != nil {
	   			return nil, err
	   		}
	   		users = append(users, user)
	   	} */

	return users, nil
}

func (u *UserRepository) GetById(id string) (*core.User, error) {
	tsql := `select Id,ConcurrencyStamp,Email,PhoneNumber,UserName from AspNetUsers where Id=?`
	user := core.User{}
	err := u.Db.Raw(tsql, id).Scan(&user).Error
	if err != nil {
		return nil, err
	}

	return &user, nil
}

func (u *UserRepository) GetByUserName(userName string) (*core.User, error) {
	tsql := "select top 1 UserName,Id from AspNetUsers where UserName = ?"
	var user core.User
	err := u.Db.Raw(tsql, userName).Scan(&user).Error
	if err != nil {
		return nil, err
	}

	return &user, nil
}
